package com.emm.yixun.system.service.impl.manage;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.NoticeTemporaryService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.model.Notice;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.NoticeTemporaryDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsReadEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.IsValidEnum;
import com.emm.yixun.common.model.enums.NoticeTypeEnum;
import com.emm.yixun.common.model.enums.ReceiveStatusEnum;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;

@Service("sysNoticeManage")
public class SysNoticeManage {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private NoticeService noticeService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private NoticeTemporaryService noticeTemporaryService;

	/**
	 * 插入消息 - 判断是否已有重复
	 * 
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO isRepeated(Map<String, String> noticeParamMap) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			NoticeDto noticeDto = new NoticeDto();
			noticeDto.setDictionaryId(Long.parseLong(noticeParamMap.get("noticeDicId")));
			noticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
			noticeDto.setNoticeTempType(noticeParamMap.get("noticeTempType"));
			noticeDto.setTitle(noticeParamMap.get("title"));
			noticeDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
			if (noticeParamMap.get("projectCode") != null) {
				noticeDto.setProjectCode(noticeParamMap.get("projectCode"));
			}
			noticeDto.setUserCode(noticeParamMap.get("userCode"));
			noticeDto.setAccessCode(noticeParamMap.get("accessCode"));
			noticeDto.setIsValid(IsValidEnum.VALID.getNo());
			noticeDto.setIsRead(IsReadEnum.UNREAD.getNo());
			noticeDto.setIsSend(IsSendEnum.UNSEND.getNo());
			noticeDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			noticeDto.setRemark(noticeParamMap.get("replaceValues"));
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String createTimeBefore =df.format(new Date())+" 00:00:00";
			String createTimeAfter =df.format(new Date())+" 23:59:59";
			noticeDto.setCreateTimeBefore(DateUtils.StringToDate(createTimeBefore, DateStyle.YYYY_MM_DD_HH_MM_SS));
			noticeDto.setCreateTimeAfter(DateUtils.StringToDate(createTimeAfter, DateStyle.YYYY_MM_DD_HH_MM_SS));
			List<Notice> list = noticeService.selectListByDto(noticeDto);
			if (list.size() > 0) {
				resDto.setResult("1");
			} else {
				resDto.setResult("0");
			}

		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("查询消息是否有重复失败");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	/**
	 * 插入消息 - 所有人
	 * 
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice(Map<String, String> noticeParamMap, List<User> userList) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 生成消息,生成接收人信息
			NoticeDto noticeDto = new NoticeDto();
			// 通知字典表中类型ID
			noticeDto.setDictionaryId(Long.parseLong(noticeParamMap.get("noticeDicId")));
			noticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
			noticeDto.setNoticeTempType(noticeParamMap.get("noticeTempType"));
			noticeDto.setTitle(noticeParamMap.get("title"));
			noticeDto.setContent(noticeParamMap.get("sendMsg"));
			noticeDto.setIssueTime(Calendar.getInstance().getTime());
			if (noticeParamMap.get("timerNotice") != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				noticeDto.setTimerNotice(sdf.parse(noticeParamMap.get("timerNotice")));
			}
			noticeDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
			if (noticeParamMap.get("projectCode") != null) {
				noticeDto.setProjectCode(noticeParamMap.get("projectCode"));
			}
			noticeDto.setUserCode(noticeParamMap.get("userCode"));
			noticeDto.setAccessCode(noticeParamMap.get("accessCode"));
			noticeDto.setIsValid(IsValidEnum.VALID.getNo());
			noticeDto.setIsRead(IsReadEnum.UNREAD.getNo());
			noticeDto.setIsSend(IsSendEnum.UNSEND.getNo());
			noticeDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
			noticeDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			noticeDto.setRemark(noticeParamMap.get("replaceValues"));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			noticeDto = noticeService.create(noticeDto);

			// 添加接收人
			if (userList != null) {
				for (User user : userList) {
					// if(!user.getId().equals(userId)){
					MessageReceiverDto msgRecDto = new MessageReceiverDto();
					msgRecDto.setNoticeId(noticeDto.getId());
					msgRecDto.setReceiverId(user.getId());
					msgRecDto.setReceiveStatus(ReceiveStatusEnum.UNRECEIVED.getNo());
					msgRecDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
					msgRecDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
					msgRecDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					msgRecDto.setUpdateTime(new Date());
					messageReceiverService.create(msgRecDto);
					// }
				}
			}
			resDto.setResult("1");
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加提醒消息失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	/**
	 * 插入消息
	 * 
	 * @param noticeParamMap
	 *            消息map,userList 接收人list
	 * @return
	 */
	public long createNoticeWithNoticeTemp(Map<String, String> noticeParamMap, List<User> userList) {
		NoticeDto noticeDto1 = new NoticeDto();
		try {
			// 生成消息,生成接收人信息
			NoticeDto noticeDto = new NoticeDto();
			// 通知字典表中类型ID
			noticeDto.setDictionaryId(Long.parseLong(noticeParamMap.get("noticeDicId")));
			noticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
			noticeDto.setNoticeTempType(noticeParamMap.get("noticeTempType"));
			noticeDto.setTitle(noticeParamMap.get("title"));
			noticeDto.setContent(noticeParamMap.get("sendMsg"));
			noticeDto.setIssueTime(Calendar.getInstance().getTime());
			if (noticeParamMap.get("timerNotice") != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				noticeDto.setTimerNotice(sdf.parse(noticeParamMap.get("timerNotice")));
			}
			noticeDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
			if (noticeParamMap.get("projectCode") != null) {
				noticeDto.setProjectCode(noticeParamMap.get("projectCode"));
			}
			noticeDto.setUserCode(noticeParamMap.get("userCode"));
			noticeDto.setAccessCode(noticeParamMap.get("accessCode"));
			noticeDto.setIsValid(IsValidEnum.VALID.getNo());
			noticeDto.setIsRead(IsReadEnum.UNREAD.getNo());
			noticeDto.setIsSend(IsSendEnum.UNSEND.getNo());
			noticeDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
			noticeDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			noticeDto.setRemark(noticeParamMap.get("replaceValues"));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			noticeDto1 = noticeService.create(noticeDto);

			// 添加接收人
			if (userList != null) {
				for (User user : userList) {
					MessageReceiverDto msgRecDto = new MessageReceiverDto();
					msgRecDto.setNoticeId(noticeDto1.getId());
					msgRecDto.setReceiverId(user.getId());
					msgRecDto.setReceiveStatus(ReceiveStatusEnum.UNRECEIVED.getNo());
					msgRecDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
					msgRecDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
					msgRecDto.setUpdateTime(new Date());
					msgRecDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					messageReceiverService.create(msgRecDto);

					/**
					 * sys_tm_notice_temporary 保存推送消息内容入库 date：2017-03-02
					 */
					NoticeTemporaryDto noticeTemporaryDto = new NoticeTemporaryDto();
					noticeTemporaryDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
					noticeTemporaryDto.setProjectCode(noticeParamMap.get("projectCode"));
					ProjectDto entity = new ProjectDto();
					entity.setProjectCode(noticeParamMap.get("projectCode"));
					Project project = projectService.selectByDto(entity);
					noticeTemporaryDto.setProjectName(project.getProjectName());
					noticeTemporaryDto.setReceiverId(user.getId());
					noticeTemporaryDto.setAction(noticeParamMap.get("title"));
					noticeTemporaryDto.setBusinessId(noticeParamMap.get("businessId"));
					noticeTemporaryDto.setPushType(noticeParamMap.get("noticeTempType"));
					if (StringUtils.isNotEmpty(noticeParamMap.get("customerId"))) {
						noticeTemporaryDto.setCustomerId(noticeParamMap.get("customerId"));
					}
					noticeTemporaryDto.setTitle(noticeDto.getTitle());
					noticeTemporaryDto.setContent(noticeDto.getContent());
					if (StringUtils.isNotEmpty(noticeParamMap.get("tempType"))) {
						noticeTemporaryDto.setTempType(noticeParamMap.get("tempType"));
						if ("2".equals(noticeParamMap.get("tempType"))) {
							noticeTemporaryDto.setRemindCategory("审核结果");
						} else if ("3".equals(noticeParamMap.get("tempType"))) {
							noticeTemporaryDto.setRemindCategory("报备消息");
						}
						noticeTemporaryDto.setRemindCategoryId(Long.valueOf(noticeParamMap.get("noticeDicId")));
					}
					noticeTemporaryDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					if(StringUtils.isNotEmpty(noticeParamMap.get("msgOrder"))){
						noticeTemporaryDto.setMsgOrder(Integer.parseInt(noticeParamMap.get("msgOrder")));
					}
					noticeTemporaryService.create(noticeTemporaryDto);
				}
			}
			return noticeDto1.getId();
		} catch (Exception e) {
			logger.error("插入app消息内容【认筹】异常:{}", e);
		}
		return noticeDto1.getId();
	}
}
